import 'dart:convert';

import 'package:flutter_li_ke_jie/entity/app_user.dart';
import 'package:flutter_li_ke_jie/utils/common_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SPUtil{
  /// 内部构造方法，可避免外部暴露构造函数，进行实例化
  SPUtil._internal();

  static late SharedPreferences _spf;

  static Future<SharedPreferences?> init() async {
    _spf = await SharedPreferences.getInstance();
    return _spf;
  }

  ///toekn
  static Future<bool> saveToken(String token) {
    return _spf.setString('token', token);
  }

  static String? getToken() {
    return _spf.getString('token');
  }

  ///设备类型
  static Future<bool> saveDevice(String device) {
    return _spf.setString('device', device);
  }

  static String? getDevice() {
    return _spf.getString('device');
  }

  static Future<bool> saveDeviceId(String deviceId) {
    return _spf.setString('deviceId', deviceId);
  }

  static String? getDeviceId() {
    return _spf.getString('deviceId');
  }

  static Future<bool> saveUserId(String userId) {
    return _spf.setString('userId', userId);
  }

  static String? getUserId() {
    return _spf.getString('userId');
  }

  static Future<bool> saveChannelId(String channelId) {
    return _spf.setString('channelId', channelId);
  }

  static String? getChannelId() {
    return _spf.getString('channelId');
  }

  static Future<bool> saveVipState(int vipState) {
    return _spf.setInt('vipState', vipState);
  }

  static int? getVipState() {
    return _spf.getInt('vipState');
  }

  static Future<bool> saveUserInfo(AppUser appUser) {
    if(appUser!=null){
      String user =jsonEncode(appUser);
      return _spf.setString('appUserInfo', user);
    }
    return Future.value(true);
  }

  static AppUser? getUserInfo() {
    String? user =  _spf.getString('appUserInfo');
    if(user!=null){
     AppUser appUser = AppUser.fromJson(jsonDecode(user));
     return appUser;
    }
    return AppUser();
  }


  //基本信息认证状态
  static Future<bool> saveAuthState(String state) {
    return _spf.setString('auth_state', state);
  }

  static String? getAuthState() {
    return _spf.getString('auth_state');
  }
}